#include "e2d/imgui/Editor.h"

bool e2d::CustomEditor::ComboEditEntity(const std::string& label, e2d::EntityMap& inst, const std::vector<std::shared_ptr<e2d::Entity>> entities)
{
	std::string entityName = inst.EntityName();

	if (ImGui::BeginCombo(label.c_str(), entityName.c_str()))
	{
		if (ImGui::Selectable("NULL", false))
		{
			inst.SetNull();
		}

		for (auto it : entities)
		{
			auto entity = it;

			if (!entity->m_Exist)
			{
				continue;
			}
			ImGui::PushID(entity.get());
			
			std::string itLabel = entity->m_Name + "(" + entity->m_UUID + ")";

			if (ImGui::Selectable(itLabel.c_str(), entity->m_UUID == inst.m_UUID))
			{
				inst.m_UUID = entity->m_UUID;
				inst.m_Entity = entity.get();
			}
			ImGui::PopID();
		}

		ImGui::EndCombo();
	}
	if (ImGui::BeginDragDropTarget()) {
		if (const ImGuiPayload* payload = ImGui::AcceptDragDropPayload("Entity")) {

			using T = std::shared_ptr<e2d::Entity>;

			const T receivedData = *(const T*)payload->Data;
			ztclog::info("entity is %s", receivedData->m_Name.c_str());

			for (const auto& it : entities)
			{
				inst = receivedData.get();

			}
		}
		ImGui::EndDragDropTarget();
	};

	return false;
}

bool e2d::CustomEditor::ComboEditEntity(const std::string& label, e2d::EntityMap& inst, const std::vector<e2d::EntityMap> entities)
{
	std::string entityName = inst.EntityName();

	if (ImGui::BeginCombo(label.c_str(), entityName.c_str()))
	{
		int index = 0;

		for (auto it : entities)
		{
			auto entity = it.m_Entity;

			if (!entity->m_Exist)
			{
				continue;
			}

			ImGui::PushID(index++);

			std::string itLabel = entity->m_Name + "(" + entity->m_UUID + ")";

			if (ImGui::Selectable(itLabel.c_str(), entity->m_UUID == inst.m_UUID))
			{
				inst.m_UUID = entity->m_UUID;
				inst.m_Entity = entity;
			}
			ImGui::PopID();

		}
		ImGui::EndCombo();
	}

	if (ImGui::BeginDragDropTarget()) {
		if (const ImGuiPayload* payload = ImGui::AcceptDragDropPayload("Entity")) {

			using T = std::shared_ptr<e2d::Entity>;

			const T receivedData = *(const T*)payload->Data;
			ztclog::info("entity is %s", receivedData->m_Name.c_str());

			for (const auto& it : entities)
			{
				if (it.m_Entity->m_UUID == receivedData->m_UUID)
				{
					inst = receivedData.get();

				}
			}

		}
		ImGui::EndDragDropTarget();
	};
	return false;
}
